package com.fengmi.job;

import cn.hutool.json.JSONUtil;
import com.api.miaosha.MiaoShaApi;
import com.fengmi.miaosha.entity.MsGoods;
import com.fengmi.util.DateUtil;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Component
public class MiaoShaJob {

    @Autowired
    private MiaoShaApi miaoShaApi;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @XxlJob("mysql2redisPer2hour")
    public void mysql2redisPer2hour(){
        //1：获取最近的5场的时间区间
        /**
         * 11.12
         * 10-12、12-14 、14-16 、 16-18、18-20
         *
         * 12:00
         * 12-14 、14-16 、 16-18、18-20、20-22
         */
        List<Date> dateMenus = DateUtil.getDateMenus();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat redisKeyFormat = new SimpleDateFormat("yyyyMMddHH");

        //获取每个场次的商品列表
        for (Date dateMenu : dateMenus) {
            String startTime = format.format(dateMenu);
            String endTime = format.format(DateUtil.addDateHour(dateMenu, 2));
            List<MsGoods> goodsList = miaoShaApi.findGoodsListByTimeFromDB(startTime, endTime);
            //存入到redis
            /**
             * 秒杀商品：（Hash）
             *
             * key：menhu:miaosha:goods:${yyyyMMddHH} 例如:menhu:miaosha:goods:2023041008
             *
             * field：${goodsId}
             *
             * value：${goodsJsonStr}
             */
            BoundHashOperations<String, Object, Object> opt =
                    stringRedisTemplate.boundHashOps("menhu:miaosha:goods:" + redisKeyFormat.format(dateMenu));

            for (MsGoods msGoods : goodsList) {
                opt.put(msGoods.getSeckillId()+"", JSONUtil.toJsonStr(msGoods));
            }

            XxlJobHelper.log("menhu:miaosha:goods:" + redisKeyFormat.format(dateMenu)+"数据成功同步到redis");

        }

    }


    public static void main(String[] args) {
        List<Date> dateMenus = DateUtil.getDateMenus();


        dateMenus.forEach(System.out::println);
    }



}
